package com.example.naciosdemo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@SpringBootApplication
@RestController
@Slf4j
public class ConsumerServiceApplication {
    @Autowired
    private DiscoveryClient discoveryClient;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(ConsumerServiceApplication.class, args);
        try {
            new ConsumerServiceApplication().get();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/")
    public String get() throws JsonProcessingException {
        List<ServiceInstance> instances = discoveryClient.getInstances("order-service");
        if (CollectionUtils.isEmpty(instances)) {
            log.info("empty !!!");
        } else {
            ObjectMapper mapper = new ObjectMapper();
            String s = mapper.writeValueAsString(instances);
            log.info("yes,got! {}",s );
            return s;
        }

        return "empty";
    }

}
